package com.lh.jsp.urlparamEncoding;

/**
 ************************************************
 ** Module : 对应页面script 中的escape 和unescape功能一样的编码和解码类
 ** Date: 2012-2-6  Time: 下午03:48:47 
 ** Author lh 
 ************************************************ 
 */
public class EscapeUnescape {

	/**
	 * 功能描述  
	 * @Author: lh  2012-2-6 下午03:48:20
	 */
	public static void main(String[] args) {
		//String yu="http:\\\\www.baidu.com\\heaction?name=李恒 &id=5454";
		String yu="http:\\\\www.baidu.com\\heaction?name=李恒 &id=5454";
		String bh=escape(yu);		
		String a="http%3A%5Cwww.baidu.comheaction%3Fname%3D%u674E%u6052%20%26id%3D5454";
		String b=unescape(a);
		System.out.println("yu="+yu);
		System.out.println("a="+yu);
		System.out.println("bh"+bh);
		if(a.endsWith(bh)){
			System.out.println("equel");
		}
		System.out.println(b);
		String dbh=unescape(bh);
		System.out.println(dbh);
		String url="http://pagead2.googlesyndication.com/pagead/ads?&client=ca-mb-pub-5574701192944858&dt=1329875228400&ip=192.168.1.10&markup=wml&output=wml&slotname=1275601717&url=http%3A%2F%2F192.168.1.34%3A8080%2FAD%2Fg.jsp&useragent=MQQBrowser%2F2.9%2FMozilla%2F5.0+%28Linux%3B+U%3B+Android+2.3.4%3B+zh-cn%3B+MT15i+Build%2F4.0.1.A.0.283%29+AppleWebKit%2F533.1+%28KHTML%2C+like+Gecko%29+Version%2F4.0+Mobile+Safari%2F533.1";
        System.out.println("url="+unescape(url));

	}
	public static String escape(String src) {
		  int i;
		  char j;
		  StringBuffer tmp = new StringBuffer();
		  tmp.ensureCapacity(src.length() * 6);
		  for (i = 0; i < src.length(); i++) {
		   j = src.charAt(i);
		   if (Character.isDigit(j) || Character.isLowerCase(j)
		     || Character.isUpperCase(j))
		    tmp.append(j);
		   else if (j < 256) {
		    tmp.append("%");
		    if (j < 16)
		     tmp.append("0");
		    tmp.append(Integer.toString(j, 16));
		   } else {
		    tmp.append("%u");
		    tmp.append(Integer.toString(j, 16));
		   }
		  }
		  return tmp.toString();
		 }
		 public static String unescape(String src) {
		  StringBuffer tmp = new StringBuffer();
		  tmp.ensureCapacity(src.length());
		  int lastPos = 0, pos = 0;
		  char ch;
		  while (lastPos < src.length()) {
		   pos = src.indexOf("%", lastPos);
		   if (pos == lastPos) {
		    if (src.charAt(pos + 1) == 'u') {
		     ch = (char) Integer.parseInt(src
		       .substring(pos + 2, pos + 6), 16);
		     tmp.append(ch);
		     lastPos = pos + 6;
		    } else {
		     ch = (char) Integer.parseInt(src
		       .substring(pos + 1, pos + 3), 16);
		     tmp.append(ch);
		     lastPos = pos + 3;
		    }
		   } else {
		    if (pos == -1) {
		     tmp.append(src.substring(lastPos));
		     lastPos = src.length();
		    } else {
		     tmp.append(src.substring(lastPos, pos));
		     lastPos = pos;
		    }
		   }
		  }
		  return tmp.toString();
		 }
}
